<?php

namespace app\config;

use Core\Result\Result;

class Token
{
    /**
     * Token配置
     *
     * @return array
     */
    public static function config()
    {
        $config = [
            'token_key' => 'ysmzshop66515819847@',
            'token_exp' => 60 * 60 * 24 * 30//过期时间30天
        ];

        return $config;
    }

    /**
     * Token生成
     *
     * @param array $userInfo 会员信息
     *
     * @return string
     */
    public static function create($userInfo)
    {
        $config = self::config();
        $userInfo['iat'] = time();  //签发时间
        $userInfo['nbf'] = time();  //生效时间
        $userInfo['exp'] = time() + $config['token_exp'];  //过期时间
        $token = Jwt::getToken($userInfo);
        return $token;
    }

    /**
     * Token验证
     *
     * @param string $token token
     *
     * @return Exception
     */
    public static function verify($token)
    {

        try {
            $config = self::config();
            $tokenInfo = Jwt::verifyToken($token);
            if(!$tokenInfo) Result::error( '登录已过期，请重新登录！',401);
            return $tokenInfo;
        } catch (\Exception $e) {
            Result::error($e->getMessage(),500);
        }
    }

    /**
     * Token会员id
     *
     * @param string $token token
     *
     * @return integer member_id
     */
    public static function userId($token)
    {
        try {
            $config = self::config();
            $tokenInfo = Jwt::verifyToken($token);
            if(!$tokenInfo) Result::error( '登录已过期，请重新登录！',401);
            $user_id = $tokenInfo['user_id'];
            return $user_id;
        } catch (\Exception $e) {
            Result::error($e->getMessage(),500);
        }
    }
}